import React, {useCallback, useEffect, useRef, useState} from "react"
import {
    deleteMarketSaleDocumentItem, downloadImportTemplate,
    getMarketSaleDocumentDetail, importMarketSaleDocumentItems,
    MarketSaleDocumentDetail,
    MarketSaleDocumentItem, submitMarketSaleDocument, updateMarketSaleDocumentItemAmount, validateMarketSaleDocument
} from "../../apis/MarketSaleDocumentApi";
import {Button, Col, Descriptions, InputNumber, Popover, Row, theme, Typography, Upload} from "antd";
import {OffsetDateTime} from "@js-joda/core";
import {
    convertAntdTableToExcelWithOptions,
    ExportedColumnProps
} from "../../utils/AntdTableUtils";
import AuthorizationResource from "../../components/AuthorizationResource";
import {DeleteOutlined, QuestionCircleOutlined, UploadOutlined} from "@ant-design/icons";
import DataPageLayout from "../../components/DataPageLayout";
import ArrayUtils from "@zxy-cn/array-utils";
import SingleInputPopover from "../../components/SingleInputPopover";
import dashboardPageStore from "../../store/DashboardPageStore";
import {observerDashboardPageWrapper} from "../../components/dashboardPages/ObserverDashboardPageWrapper";
import employeeAuthorizationStore from "../../store/EmployeeAuthorizationStore";
import LoadableButton from "../../components/LoadableButton";
import {saveTo, saveWorkbookTo} from "../../utils/FileSaver";
import GoodsTable from "../../components/GoodsTable";
import useMessage from "antd/es/message/useMessage";
import {ErrorResponse} from "@zxy-cn/fetcher";
import TableColumnSelectModal from "../TableColumnSelectModal";
import {DATE_WITH_TIME_FORMATER} from "../../utils/Date";


export interface pageProps {
    id: number
}

const myPath = "markets/accounts/saleDocuments/{id}"

const MarketSaleDocumentDetailPage: React.FC<pageProps> = ({id}) => {
    const [loading, setLoading] = useState(false)
    const [data, setData] = useState<MarketSaleDocumentDetail>()
    const query = useCallback(() => {
        setLoading(true)
        getMarketSaleDocumentDetail(id).then(response => {
            dashboardPageStore.setTitle(myPath.replace("{id}", id.toString()), response.data.market.name + "销售单")
            setData(response.data)
        }).finally(() => {
            setLoading(false)
        })
    }, [id])

    useEffect(() => {
        query()
    }, [query]);

    let token = theme.useToken();

    let columnsRef = useRef<ExportedColumnProps<MarketSaleDocumentItem>[]>();
    const [importing, setImporting] = useState(false)
    let [messageApi,messageHolder] = useMessage();
    const [openExportColumnSelectModal,setOpenExportColumnSelectModal] = useState(false)
    return (
        <>
            {messageHolder}
            {!loading ? <Descriptions title={"订单明细"}>
                <Descriptions.Item label={"卖场"}>{data?.market?.name}</Descriptions.Item>
                <Descriptions.Item label={"户头"}>{data?.account?.name}</Descriptions.Item>
                <Descriptions.Item label={"下单人"}>{data?.createdBy?.name}</Descriptions.Item>
                {!!data?.createdDateTime && <Descriptions.Item
                    label={"月份"}>{data?.year-data?.month}</Descriptions.Item>}
                {!!data?.submittedDateTime && <Descriptions.Item
                    label={"下单时间"}>{data?.submittedDateTime.format(DATE_WITH_TIME_FORMATER)}</Descriptions.Item>}
                {!!data?.auditedDateTime ? <Descriptions.Item
                    label={"审核时间"}>{data.auditedDateTime.format(DATE_WITH_TIME_FORMATER)}</Descriptions.Item> : undefined}
            </Descriptions> : null}
            <Row gutter={8} style={{margin: "12px 0"}}>
                <Col>
                    <TableColumnSelectModal availableColumns={["名称","条码","数量","金额小计","特价计算","品牌","类别","厂商","库存","零售价","箱规"]} open={openExportColumnSelectModal} onConfirm={async fields => {
                        let columns = Array.from(columnsRef.current!!);
                        let priceDifference = "priceDifference";
                        ArrayUtils.insertAfter(columns, value => value.title==="金额小计",{
                            title:"特价计算",
                            key: priceDifference,
                            generateExcelValue: (_, value: MarketSaleDocumentItem) => {
                                return (value.amountInOrder?(value.totalFee/value.amountInOrder - value.price).toFixed(2) :"").toString()
                            },
                        })
                        let workbook = await convertAntdTableToExcelWithOptions(columns, data?.items ?? [], {selectedColumns: fields,postHandler:(workshet,data)=>{
                            let lastRowNumber = workshet.rowCount;
                                let priceDifferenceIndex = columns.findIndex(it=>it.key === priceDifference);
                                if(priceDifferenceIndex!=-1){
                                    let cell = workshet.getCell(lastRowNumber+1,priceDifferenceIndex+1);
                                    cell.value = "特价合计："+ArrayUtils.sum(data,item => (item.totalFee/item.amountInOrder - item.price)<-item.price * 0.1?item.totalFee:0).toFixed(2)
                                }

                                const feeSumIndex = columns.findIndex(it=>it.dataIndex === "totalFee");
                                if(feeSumIndex!=-1){
                                    let cell = workshet.getCell(lastRowNumber+1,feeSumIndex+1);
                                    cell.value = +ArrayUtils.sum(data,item => item.totalFee).toFixed(2)
                                }
                            }},);
                        // await saveWorkbookTo(workbook, `${data?.market?.name}${data?.account?.name}销售记录-${data!.startDateTime.format(DATE_WITH_TIME_FORMATER)} - ${data?.endDateTime?data?.endDateTime.format(DATE_WITH_TIME_FORMATER):""}`)
                        setOpenExportColumnSelectModal(false)
                    }} cacheKey={"marketSaleDocument"} onCancel={_=>setOpenExportColumnSelectModal(false)}/>
                    <LoadableButton onClick={async (_) => {
                        setOpenExportColumnSelectModal(true)
                    }}>
                        导出
                    </LoadableButton>


                </Col>
                <Col>
                    <Row>
                        <Upload fileList={[]}
                                accept={"application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}
                                maxCount={1}
                                beforeUpload={file => {
                                    setImporting(true)
                                    importMarketSaleDocumentItems(id, file).then(response => {
                                        query()
                                    }).catch((response:ErrorResponse)=>{
                                        if(typeof response ==="object"){
                                            messageApi.error(JSON.stringify(response.data))
                                        }
                                    }).finally(() => {
                                        setImporting(false)
                                    });
                                    return false
                                }}>
                            <Button icon={<UploadOutlined/>} loading={importing}>导入</Button>
                        </Upload>
                        <Popover title={"导入货品"} content={
                            <Typography>
                                <Typography.Paragraph>
                                    按照约定的格式上传excel文件。
                                    <Typography.Link onClick={() => {
                                        downloadImportTemplate().then(res => res.data)
                                            .then(blob => {
                                                saveTo(blob, "导入销售数据模板.xlsx")
                                            })

                                    }}>下载模板</Typography.Link>
                                </Typography.Paragraph>
                                <Typography.Paragraph>
                                    <ul>
                                        <li>只能导入已有资料的商品</li>
                                        <li>条码不可重复</li>
                                        <li>已存在的商品会被忽略</li>
                                        <li>仅使用文件的第一个Sheet</li>
                                    </ul>
                                </Typography.Paragraph>
                            </Typography>
                        }><QuestionCircleOutlined/></Popover></Row>
                </Col>
                {employeeAuthorizationStore.hasAuthority("卖场_销售单_审核")
                && !data?.auditedDateTime
                && !!data?.submittedDateTime ?
                    <Col>
                        <LoadableButton onClick={async () => {
                            await validateMarketSaleDocument(id)
                            setData({...data!, auditedDateTime: OffsetDateTime.now()})
                        }}>验收</LoadableButton>
                    </Col> : undefined}
                {employeeAuthorizationStore.hasAuthority("卖场_销售单_开单") && !data?.submittedDateTime &&
                    <Col>
                        {!!data && <LoadableButton onClick={async (event) => {
                            await submitMarketSaleDocument(data?.id)
                            setData({...data!, submittedDateTime: OffsetDateTime.now()})
                        }}>
                            提交订单
                        </LoadableButton>}

                    </Col>}
                {<Col>
                    <LoadableButton onClick={async (_) => {
                        // await submitMarketSaleDocument(id)
                        // setData({...data!, submitDateTime: OffsetDateTime.now()})
                    }}>
                        打印
                    </LoadableButton></Col>}
            </Row>

            {/*{((employeeAuthorizationStore.hasAuthority("卖场_销售单_开单") && !data?.submittedDateTime) || (employeeAuthorizationStore.hasAuthority("卖场_销售单_修改") && !data?.auditedDateTime)) &&*/}
            {/*    !!data &&*/}
            {/*    <EditOrderItemRow<AddMarketSaleDocumentItemRequest, GoodsWithMarketInStore>*/}
            {/*        request={{editMarketSaleDocumentId: id}}*/}
            {/*        fetchGoods={() =>*/}
            {/*            getAllGoodsWithMarketInStoreInMakret(data.market.id).then(res => {*/}
            {/*                return res.data*/}
            {/*            })}*/}
            {/*        optionRender={it => <div style={{display: 'flex', flexDirection: "column"}}>*/}
            {/*            <div style={{display: "flex", justifyContent: 'space-between'}}>*/}
            {/*                <span>{it.barcode}</span><span>{it.name}</span>*/}
            {/*            </div>*/}
            {/*            <Space size={24}><span>卖场存货:{it.amountInMarket ?? "无"}</span><span>库存:{it.amount}</span></Space>*/}
            {/*        </div>}*/}
            {/*        onFinish={async (values) => {*/}
            {/*            return addMarketSaleDocumentItem(id, values).then(() => {*/}
            {/*                query()*/}
            {/*            })*/}
            {/*        }} existedGoodsIds={data?.items?.map(it => it.id) ?? []}/>}*/}
            <DataPageLayout leftActions={<>
            </>}>

                <GoodsTable<MarketSaleDocumentItem> loading={loading}
                                                    size={"small"}
                                                    customColumns={columns => {
                                                        ArrayUtils.insertAfter(columns, value => value.dataIndex === "name", {
                                                            dataIndex: "amountInOrder",
                                                            title: "数量",
                                                        },)
                                                        ArrayUtils.insertAfter(columns, value => value.dataIndex === "amountInOrder", {
                                                            dataIndex: "totalFee",
                                                            title: "金额小计",
                                                        },)
                                                        columns.push({
                                                            ignoreInExcel: true,
                                                            title: "操作",
                                                            render: (_, item, index) => {
                                                                return <>
                                                                    {employeeAuthorizationStore.hasAuthority("卖场_销售单_开单") && !data?.auditedDateTime &&
                                                                        <SingleInputPopover required title={"修改单品数量"}
                                                                                            rules={[{
                                                                                                type: "number",
                                                                                                min: 0
                                                                                            }]}
                                                                                            onConfirm={async value => {
                                                                                                let amount = parseInt(value);
                                                                                                await updateMarketSaleDocumentItemAmount(id, item.id, {amount})
                                                                                                let items = Array.from(data?.items ?? []);
                                                                                                items[index].amountInOrder = amount
                                                                                                setData({
                                                                                                    ...data!,
                                                                                                    items
                                                                                                })
                                                                                            }} fieldName={"货品数量"}
                                                                                            customInput={(props, ref) => {
                                                                                                return <InputNumber
                                                                                                    placeholder={props.placeholder}
                                                                                                    style={{width: "100%"}}
                                                                                                    autoFocus={props.autoFocus}
                                                                                                    min={0}
                                                                                                    defaultValue={1}/>
                                                                                            }}>
                                                                            <Button type={"link"}>修改数量</Button>
                                                                        </SingleInputPopover>}

                                                                    <AuthorizationResource
                                                                        authorities={["卖场_销售单_修改"]}>
                                                                        <Button type={"link"}
                                                                                danger
                                                                                onClick={() => {
                                                                                    deleteMarketSaleDocumentItem(id, item.id).then(() => {
                                                                                        let items = Array.from(data!.items);
                                                                                        ArrayUtils.remove(items, item)
                                                                                        setData({
                                                                                            ...data!,
                                                                                            items
                                                                                        })
                                                                                    })
                                                                                }}>
                                                                            <DeleteOutlined/>
                                                                            删除
                                                                        </Button>
                                                                    </AuthorizationResource>
                                                                </>
                                                            }

                                                        },);
                                                        columnsRef.current = columns;
                                                        return columns;
                                                    }}
                                                    rowKey={"id"} data={data?.items ?? []}>
                </GoodsTable>
            </DataPageLayout>

        </>
    )
}

export default observerDashboardPageWrapper(MarketSaleDocumentDetailPage, myPath, "卖场销售详情")

